package com.panda.web.utils;

import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;

@Component
public class XmlUtils {

    public static Map<String, String> xmlToMap(String xml) throws Exception {
        Map<String, String> map = new HashMap<>();
        if (xml == null || xml.trim().isEmpty()) {
            throw new IllegalArgumentException("XML content is empty");
        }

        // 进行日志输出，检查 XML 格式
        System.out.println("Received XML: " + xml);

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 处理可能的异常
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    map.put(node.getNodeName(), node.getTextContent());
                }
            }
        } catch (Exception e) {
            // 捕获并打印错误，防止程序崩溃
            System.err.println("XML Parsing Error: " + e.getMessage());
            throw e;
        }

        return map;
    }
}